#
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
#

"""
await表达式发射器

将await表达式编译为C++代码。
"""

from mcpy.ir.expressions.await_expr import IRAwait
from ..core.emitter import NodeTypeEmitter, EmitResult
from ..core.context import CodeGenContext
from ..core.generator import get_global_generator
from ...codegen.configs.operators import get_operator_precedence


class AwaitEmitter(NodeTypeEmitter):
    """await表达式发射器
    
    在异步函数转换Pass中，await表达式应该被转换为then链。
    这个发射器主要用于简单场景或者调试模式，直接生成.get()同步等待。
    """
    
    def __init__(self):
        super().__init__([IRAwait])
    
    def emit(self, node: IRAwait, context: CodeGenContext) -> EmitResult:
        """生成await表达式代码
        
        Args:
            node: await表达式节点
            context: 代码生成上下文
            
        Returns:
            生成的代码结果
        """
        generator = get_global_generator()
        
        # 生成被await的表达式
        value_code = generator.generate_expression(node.value, context)
        
        # 检查被 await 的表达式类型，只有 mc::future 才需要 .get()
        value_cpp_type = context.get_cpp_type(node.value)
        if value_cpp_type and value_cpp_type.startswith("mc::future"):
            code = f"{value_code}.get()"
        else:
            # 非 future：直接使用值表达式
            code = value_code
        
        # 需要mc::future头文件
        context.require_include("mc/future.h")
        
        return EmitResult(
            code=code,
            precedence=get_operator_precedence("call")
        )
    
    def get_priority(self) -> int:
        """await发射器的优先级"""
        return 50  # 中等优先级

